<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.6.8/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
    <style>
        body {
            background-color: #ffffff;
        }
        .layui-table-cell {
            text-align:center;
            height: auto;
            white-space: normal;
        }
        .layui-table img {
            max-width: 300px;
        }
    </style>
</head>
<body>

<div class="layui-tab layui-tab-brief">
    <ul class="layui-tab-title">
        <li class="layui-this">基础信息</li>
        <li>主体内容</li>
    </ul>
    <div class="layui-tab-content" style="height: 100px;">
        <div class="layui-tab-item layui-show">
            <div class="layui-form layuimini-form" lay-filter="itemEdit">
                <div class="layui-form-item">
                    <label class="layui-form-label">ID</label>
                    <div id="id_div_id" style="line-height: 38px; font-weight: bold;">...</div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">栏目</label>
                    <div class="layui-input-block" id="id_div_menu_select" style="width: 600px;">
                        加载中...
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">标题</label>
                    <div class="layui-input-block" style="width: 600px;">
                        <input type="hidden" name="id" id="id_hidden_id" value="" />
                        <input type="text" name="title" autocomplete="off" placeholder="非必填" class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">副标题</label>
                    <div class="layui-input-block" style="width: 600px;">
                        <input type="text" name="title_short" autocomplete="off" placeholder="非必填" class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">封面</label>
                    <div class="layui-input-block" style="width: 600px;">
                        <input type="text" value="" name="image_cover" id="id_hidden_image_cover" class="layui-input" placeholder="直接输入图片 URL" />
                        <div class="layui-upload" style="margin-top: 5px;">
                            <button type="button" class="layui-btn layui-btn-xs" id="id_btn_upload">上传图片</button>
                            <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" onclick="javascript:layui.cancelImageCover();">取消图片</button>
                            <div class="layui-upload-list">
                                <img class="layui-upload-img" id="id_img_image_cover" src="" style="width: 100px; height: 100px; display: none;" />
                                <p id="id_p_upload"></p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">来源</label>
                    <div class="layui-input-block" style="width: 600px;">
                        <input type="text" name="source_from" autocomplete="off" placeholder="非必填" class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">标签</label>
                    <div class="layui-input-block" style="width: 600px;">
                        <input type="text" name="tag_names" autocomplete="off" placeholder="非必填，多个以逗号隔开。" class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">生效开始</label>
                    <div class="layui-input-block" style="width: 200px;">
                        <input type="text" class="layui-input" id="id_input_enable_start" placeholder="非必填" />
                        <input type="hidden" name="enable_start" id="id_hidden_enable_start" value="" />
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">生效结束</label>
                    <div class="layui-input-block" style="width: 200px;">
                        <input type="text" class="layui-input" id="id_input_enable_end" placeholder="非必填" />
                        <input type="hidden" name="enable_end" id="id_hidden_enable_end" value="" />
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block" id="id_div_status_select" style="width: 200px;">
                        加载中...
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">查看数</label>
                    <div id="id_div_viewed_count" title="数据有缓存，非实时数据" style="line-height: 38px;">...</div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">点赞数</label>
                    <div id="id_div_liked_count" title="数据有缓存，非实时数据" style="line-height: 38px;">...</div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">创建时间</label>
                    <div id="id_div_created_at" style="line-height: 38px;">...</div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">最近更新</label>
                    <div id="id_div_updated_at" style="line-height: 38px;">...</div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">删除时间</label>
                    <div id="id_div_deleted_at" style="line-height: 38px;">...</div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">被锁定</label>
                    <div id="id_div_locked_by_admin" style="line-height: 38px;">...</div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-tab-item">
            <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
        </div>
    </div>
</div>

<script src="/lib/layui-v2.6.8/layui.js" charset="utf-8"></script>
<script src="/js/lay-config.js?v=2.0.0" charset="utf-8"></script>
<script>
    layui.use(['form', 'upload', 'laydate', 'element', 'table'], function () {
        var form = layui.form,
            layer = layui.layer,
            upload = layui.upload,
            laydate = layui.laydate,
            element = layui.element,
            table = layui.table,
            $ = layui.jquery;

        $.get('/admin/user/getCurrent', {}, function (re) {
            if (re.code == 0) {
                layui.use('watermark', function (watermark) {
                    watermark({watermark_txt: re.data.name});
                });
            }
        }, 'json');

        layui.cancelImageCover = function () {
            if ($('#id_hidden_image_cover').val() == '') {
                return false;
            }
            layer.confirm('真的要取消吗？保存后不能恢复。', function (index) {
                $('#id_img_image_cover').attr('src', '');
                $('#id_img_image_cover').hide();
                $('#id_hidden_image_cover').val('');
                layer.close(index);
            });
        }

        layui.openEditor = function (contentId, ideId) {
            layer.open({
                title: '编辑内容',
                type: 2,
                shadeClose: true,
                area: ['100%', '100%'],
                content: 'editor_' + ideId + '.html#/id=' + contentId,
            });
        }

        let id = layui.router().search.id;
        if (id == '' || isNaN(id)) {
            layer.alert('页面参数错误,请检查!');
            return false;
        } else {
            $('#id_hidden_id').val(id);
            $('#id_div_id').html(id);
        }

        laydate.render({
            elem: '#id_input_enable_start'
            ,type: 'datetime'
            ,done: function (value, dt) {
                $('#id_hidden_enable_start').val(value);
            }
        });

        laydate.render({
            elem: '#id_input_enable_end'
            ,type: 'datetime'
            ,done: function (value, dt) {
                $('#id_hidden_enable_end').val(value);
            }
        });

        let allStatusOptions = '';
        $.get('/admin/item/getAllStatus', {}, function (re) {
            if (re.code == 0) {
                for (let i in re.data) {
                    allStatusOptions += '<option value="' + i + '">' + re.data[i] + '</option>';
                }
                $('#id_div_status_select').html('<select name="status" class="layui-select">' + allStatusOptions + '</select>');
            } else {
                layer.msg('加载状态失败!');
            }
        }, 'json');

        $.get('/admin/menu/getAllAsSelect', {}, function (re) {
            if (re.code == 0) {
                let select = '<select name="menu_id" class="layui-select"><option value="">-- 选择 --</option>';
                select += '<option value="0">├─ 未归类文章</option>';
                for (let i in re.data) {
                    select += '<option value="' + re.data[i].id + '">' + re.data[i].name + '</option>';
                }
                select += '</select>';
                $('#id_div_menu_select').html(select);
                form.render();
                $.get('/admin/item/info', {'id': id}, function (re) {
                    if (re.code == 0) {
                        form.val('itemEdit', re.data);
                        $('#id_div_viewed_count').html(re.data.viewed_count);
                        $('#id_div_liked_count').html(re.data.liked_count);
                        $('#id_input_enable_start').val(re.data.enable_start);
                        $('#id_input_enable_end').val(re.data.enable_end);
                        if (re.data.image_cover != '') {
                            $('#id_img_image_cover').attr('src', re.data.image_cover);
                            $('#id_img_image_cover').show();
                        }
                        $('#id_div_created_at').html(re.data.created_at);
                        $('#id_div_updated_at').html(re.data.updated_at);
                        $('#id_div_deleted_at').html(re.data.deleted_at);
                        $('#id_div_locked_by_admin').html(re.data.locked_by_admin);
                        table.render({
                            elem: '#currentTableId',
                            url: '/admin/item/getAllContentsById',
                            where: {
                                'id': id
                            },
                            cols: [[
                                {field: 'id', title: 'ID', width: 60, style: 'height: 280px;'},
                                {field: 'image_inner', width: 320, title: '<i class="layui-icon layui-icon-upload-drag"></i>图片上传', templet: function (row) {
                                    let src = row.image_inner;
                                    if (row.image_inner === undefined) {
                                        src = '';
                                    }
                                    let html = '<img id="id_img_upload_' + row.id + '" src="' + src + '" style="width: 300px; height: 200px; display: ' + (src == '' ? 'none' : 'block') + '" />';
                                    html += '<button type="button" id="id_btn_upload_' + row.id + '" class="layui-btn layui-btn-normal layui-btn-xs my-upload-btn"><i class="layui-icon layui-icon-upload-drag"></i>上传</button>';
                                    return html;
                                }},
                                {field: 'image_link', title: '<i class="layui-icon layui-icon-edit"></i>图片跳转链接 (单击编辑保存)', edit: 'text', templet: function (row) {
                                    if (row.image_link === undefined || row.image_link == '') {
                                        return row.id > 0 ? '待编辑' : '待编辑以创建';
                                    }
                                    return row.image_link;
                                }},
                                {field: 'content_short', title: '<i class="layui-icon layui-icon-edit"></i>内容简要 (单击编辑保存)', edit: 'text', templet: function (row) {
                                    if (row.content_short === undefined || row.content_short == null || row.content_short == '') {
                                        return row.id > 0 ? '待编辑' : '待编辑以创建';
                                    }
                                    return row.content_short;
                                }},
                                {title: '<i class="layui-icon layui-icon-edit"></i>内容主体', templet: function (row) {
                                    if (row.id == 0) {
                                        return '';
                                    }
                                    let buttons = '<button style="float:left;" class="layui-btn layui-btn-xs layui-btn-normal" onclick="javascript:layui.openEditor(' + row.id + ', 0);"><i class="layui-icon layui-icon-edit"></i>文本框编辑' + (row.content_ide == 0 ? ' (上次使用)' : '') + '</button><br />';
                                    buttons += '<button style="float:left;" class="layui-btn layui-btn-xs layui-btn-normal" onclick="javascript:layui.openEditor(' + row.id + ', 1);"><i class="layui-icon layui-icon-edit"></i>可视化编辑' + (row.content_ide == 1 ? ' (上次使用)' : '') + '</button><br />';
                                    buttons += '<button style="float:left;" class="layui-btn layui-btn-xs layui-btn-normal" onclick="javascript:layui.openEditor(' + row.id + ', 2);"><i class="layui-icon layui-icon-edit"></i>Markdown编辑' + (row.content_ide == 2 ? ' (上次使用)' : '') + '</button>';
                                    return buttons;
                                }},
                                {field: 'page_number', width: 90, title: '<i class="layui-icon layui-icon-edit"></i>页序', edit: 'text'},
                                {title: '删除', width:90, templet: function (row) {
                                    if (row.id == id) {
                                        return '';
                                    }
                                    if (row.id == 0) {
                                        return '<button type="button" class="layui-btn layui-btn-xs layui-btn-normal" onclick="javascript:layui.newContent();"><i class="layui-icon layui-icon-add-1"></i>新增</button>';
                                    }
                                    return '<button class="layui-btn layui-btn-danger layui-btn-xs" onclick="javascript:layui.deleteContent(' + row.id + ');"><i class="layui-icon layui-icon-delete"></i>删除</button>';
                                }}
                            ]],
                            limit: 10000,
                            page: false,
                            skin: 'line',
                            done: function () {
                                $('body, html').animate({
                                    scrollTop: 0
                                }, 100);
                                upload.render({
                                    elem: '.my-upload-btn'
                                    ,url: '/admin/static/create'
                                    ,before: function(obj) {
                                        let imgId = '#' + (this.item[0].id).replace('btn', 'img');
                                        obj.preview(function(index, file, result){
                                            $(imgId).attr('src', result); //图片链接（base64）
                                            $(imgId).show();
                                        });
                                    }
                                    ,done: function(res) {
                                        if(res.code != 0) { // 上传失败
                                            layer.msg(res.msg);
                                            return false;
                                        }
                                        layer.msg('上传成功。');
                                        let rowId = (this.item[0].id).replace('id_btn_upload_', '');
                                        rowId = parseInt(rowId);
                                        let url = '/admin/item/' + (rowId == 0 ? 'create' : 'update');
                                        let data = {'image_inner': res.data.src};
                                        if (rowId == 0) {
                                            data['main_id'] = id;
                                            data['page_number'] = 1;
                                        } else {
                                            data['id'] = rowId;
                                        }
                                        $.post(url, data, function (re) {
                                            if (re.code == 0) {
                                                layer.msg('保存成功');
                                                if (rowId == 0) {
                                                    table.reload('currentTableId');
                                                }
                                            } else {
                                                layer.msg('数据保存失败, ' + re.msg);
                                                table.reload('currentTableId');
                                            }
                                        }, 'json');
                                    }
                                });
                            }
                        });
                    } else {
                        layer.msg('内容加载失败！');
                    }
                }, 'json');
            } else {
                layer.msg('栏目选择下拉框加载失败！');
            }
        }, 'json');

        // 图片上传
        let uploadInst = upload.render({
            elem: '#id_btn_upload'
            ,url: '/admin/static/create'
            ,before: function(obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#id_img_image_cover').attr('src', result); //图片链接（base64）
                    $('#id_img_image_cover').show();
                });
            }
            ,done: function(res) {
                if(res.code != 0) { // 上传失败
                    return layer.msg(res.msg);
                }
                layer.msg('上传成功。');
                $('#id_hidden_image_cover').val(res.data.src);
            }
            ,error: function() {
                let reUpload = $('#id_p_upload');
                reUpload.html('<span style="color: #ff5722;">上传失败</span> <a class="layui-btn layui-btn-xs upload-reload">重试</a>');
                reUpload.find('.upload-reload').on('click', function() {
                    uploadInst.upload();
                });
            }
        });

        // 监听提交
        form.on('submit(saveBtn)', function (data) {
            let loading = layer.load(2);
            delete data.field.file;
            data = data.field;
            $.post('/admin/item/update', data, function (re) {
                if (re.code == 0) {
                    layer.msg('保存成功');
                } else {
                    layer.msg('保存失败, 信息: ' + re.msg);
                }
                layer.close(loading);
            }, 'json');
            return false;
        });

        /* 监听删除 */
        layui.deleteContent = function (rowId) {
            layer.confirm('真的要删除吗?', function (index) {
                $.post('/admin/item/delete', {'id': rowId, 'force': 1}, function (re) {
                    if (re.code == 0) {
                        layer.msg('删除成功');
                        table.reload('currentTableId');
                    } else {
                        layer.msg('删除失败, ' + re.msg);
                    }
                }, 'json');
                layer.close(index);
            });
        };

        layui.newContent = function () {
            $.post('/admin/item/create', {
                'main_id': id,
                'page_number': 1
            }, function (re) {
                if (re.code == 0) {
                    layer.msg('新增成功');
                    table.reload('currentTableId');
                } else {
                    layer.msg('新增失败');
                }
            }, 'json');
        };

        /* 监听单元格编辑 */
        table.on('edit(currentTableFilter)', function(obj) {
            let field = obj.field;
            let rowId = obj.data.id;
            let newValue = obj.value.trim();
            let mainId = obj.data.main_id;
            if (field == 'page_number') {
                if (rowId == id) {
                    layer.msg('此行默认为"0", 不能修改!');
                    table.reload('currentTableId');
                    return false;
                }
                if (newValue == '' || isNaN(newValue) || newValue == 0) {
                    layer.msg('请输入大于"0"的值!');
                    table.reload('currentTableId');
                    return false;
                }
            }
            let url = '/admin/item/' + (rowId == 0 ? 'create' : 'update');
            let data = {};
            data[field] = newValue;
            if (rowId == 0) {
                data['main_id'] = mainId;
                if (field != 'page_number') {
                    data['page_number'] = 1;
                }
            } else {
                data['id'] = rowId;
            }
            $.post(url, data, function (re) {
                if (re.code == 0) {
                    layer.msg('保存成功');
                    if (rowId == 0) {
                        table.reload('currentTableId');
                    }
                } else {
                    layer.msg('保存失败, ' + re.msg);
                    table.reload('currentTableId');
                }
            }, 'json');
        });

    });
</script>
</body>
</html>